package com.prestamomo.vil.ppa.pmvilmedium.pmvilarm.pmother;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Build;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.os.ConfigurationCompat;
import androidx.core.os.LocaleListCompat;

import com.prestamomo.vil.ppa.PmvilApp;
import com.prestamomo.vil.ppa.pmvilmedium.PmvilImeiMd;
import com.prestamomo.vil.ppa.pmvilmedium.pmvilarm.pmnet.PmvilNetInfoMd;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;

public class PmvilGeneralMd {
    private static JSONObject generalPmvilInfo = null;
    private static TelephonyManager telephonyPmvilManager;

    public static JSONObject getGeneraPmvilInfo(Context pmvilCntext) throws JSONException {
        telephonyPmvilManager = (TelephonyManager) pmvilCntext.getSystemService(Context.TELEPHONY_SERVICE);
        if (generalPmvilInfo == null)  generalPmvilInfo = new JSONObject();

        generalPmvilInfo.put("acwwybv", PmvilApp.pmvilAdid);//gaid
        String androidPmvilId = Settings.Secure.getString(pmvilCntext.getContentResolver(), Settings.Secure.ANDROID_ID);
        generalPmvilInfo.put("kvjtkboq", androidPmvilId);//android_id--and_id
        if(TextUtils.isEmpty(PmvilImeiMd.getDeviceIMEI())){
            generalPmvilInfo.put("ikshyjqp", androidPmvilId);//imei
        }else {
            generalPmvilInfo.put("ikshyjqp", PmvilImeiMd.getDeviceIMEI());//imei
        }
        generalPmvilInfo.put("sfasmwfoq", telephonyPmvilManager.getPhoneType());//phone_type
        generalPmvilInfo.put("hhpfkib", PmvilNetInfoMd.getMacPmvilAddress(PmvilApp.getPmvilApss()));//mac--mac
        generalPmvilInfo.put("cdknxxdod",  getPmvilLanguage().get(0));//locale_iso_3_language
        generalPmvilInfo.put("jjhkdet",  getPmvilLanguage().get(1));//locale_display_language
        generalPmvilInfo.put("oecim",  getPmvilLanguage().get(2));//locale_iso_3_country
        generalPmvilInfo.put("jutealtmb",  getPmvilLanguage().get(3));//language--language
        generalPmvilInfo.put("flonvvfi", "");//phone_number
        generalPmvilInfo.put("piosnxw", telephonyPmvilManager.getNetworkOperatorName());//network_operator_name
        generalPmvilInfo.put("kbgnyix", ActivityCompat.checkSelfPermission(pmvilCntext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                ?"":telephonyPmvilManager.getNetworkType()+"");//network_type
        generalPmvilInfo.put("ewltnal", TimeZone.getDefault().getID());//time_zone_Id
        generalPmvilInfo.put("mvmnoiauc", isWifiPmvilProxy(pmvilCntext));//is_using_proxy_port
        generalPmvilInfo.put("tqfcw", isPmvilVPN(pmvilCntext));//--is_using_vpn
        try {
            generalPmvilInfo.put("yjttew", Settings.Secure.getInt(pmvilCntext.getContentResolver(), Settings.Global.ADB_ENABLED, 0) > 0);//--is_usb_debug
        }catch (Exception e){
            generalPmvilInfo.put("yjttew", false);//--is_usb_debug
        }
        generalPmvilInfo.put("oxadae", SystemClock.elapsedRealtime());//--elapsed_realtime
        generalPmvilInfo.put("rbhezvxce", getSensorPmvilList(pmvilCntext));//--sensor_list
        generalPmvilInfo.put("htgeulw", Build.MANUFACTURER);//--manufacturer
        generalPmvilInfo.put("phgocadnt", telephonyPmvilManager.getNetworkOperator());//（MCC + MNC）--network_operator
        generalPmvilInfo.put("bahkzes", TextUtils.isEmpty(telephonyPmvilManager.getNetworkOperator()) ?"":Integer.parseInt(telephonyPmvilManager.getNetworkOperator().substring(0, 3)));//mcc--mcc
        generalPmvilInfo.put("lyraby", "");//--cid
        generalPmvilInfo.put("mkndqrjgm", getUniquePmvilID());//--uuId
        return generalPmvilInfo;
    }

    //生成uuid
    public static String getUniquePmvilID() {
        String pmvil_devIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10)
                + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
        String pmvilSerial = "serial";
        pmvilSerial = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)?getPmvilKKSerial():Build.SERIAL;
        return new UUID(pmvil_devIDShort.hashCode(), pmvilSerial.hashCode()).toString();
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static String getPmvilKKSerial() {
        String pmvilSerial = "serial";
        try {
            pmvilSerial = Build.getSerial();
        } catch (Exception e) {
            pmvilSerial = "serial";
        }
        return pmvilSerial;
    }
    //传感器
    private static JSONArray getSensorPmvilList(Context pmvilCntext) throws JSONException {
        //传感器列表
        List<Sensor> sensorPmvilList = ( (SensorManager) pmvilCntext.getSystemService(Context.SENSOR_SERVICE)).getSensorList(Sensor.TYPE_ALL);
        JSONArray sensorPmvilEntList = new JSONArray();
        for (int i = 0; i < sensorPmvilList.size(); i++) {
            JSONObject sensorPmvilObj = new JSONObject();
            sensorPmvilObj.put("oxishefxu", sensorPmvilList.get(i).getType());//type--type
            sensorPmvilObj.put("vietzfsk", sensorPmvilList.get(i).getName());//name--name
            sensorPmvilObj.put("qwgoqiwe", sensorPmvilList.get(i).getVersion());//version--version
            sensorPmvilObj.put("vnhjmx", sensorPmvilList.get(i).getVendor());//vendor--vendor
            sensorPmvilObj.put("qnqyhc", sensorPmvilList.get(i).getMaximumRange());//maxRange--maxRange
            sensorPmvilObj.put("nudtbx", sensorPmvilList.get(i).getMinDelay());//minDelay--minDelay
            sensorPmvilObj.put("uhqftdv", sensorPmvilList.get(i).getPower());//power--power
            sensorPmvilObj.put("yqcfwpca", sensorPmvilList.get(i).getResolution());//resolution--resolution
            sensorPmvilEntList.put(sensorPmvilObj);
        }
        return sensorPmvilEntList;
    }



    private static List<String> getPmvilLanguage() {
        Locale pmvilLocale;
        List<String> pmvilLangueList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleListCompat localeList = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration());
            pmvilLocale = (localeList.size() > 0)?localeList.get(0):null;
        } else {
            pmvilLocale = Locale.getDefault();
        }
        pmvilLangueList.add(pmvilLocale == null?"":pmvilLocale.getISO3Language());
        pmvilLangueList.add(pmvilLocale == null?"":pmvilLocale.getDisplayLanguage());
        pmvilLangueList.add(pmvilLocale == null?"":pmvilLocale.getISO3Country());
        pmvilLangueList.add(pmvilLocale == null?"":pmvilLocale.getLanguage());
        return pmvilLangueList;
    }

    /*
     * 判断设备 是否使用代理上网
     */
    private static boolean isWifiPmvilProxy(Context pmvilCext) {
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            String portStr = System.getProperty("http.proxyPort");
            int proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
            return (!TextUtils.isEmpty(System.getProperty("http.proxyHost"))) && (proxyPort != -1);
        } else {
            return (!TextUtils.isEmpty(android.net.Proxy.getHost(pmvilCext))) && (android.net.Proxy.getPort(pmvilCext) != -1);
        }
    }

    // 判断设备是否使用 VPN
    private static boolean isPmvilVPN(Context pmvilCext) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ConnectivityManager connectyPmvilManger = (ConnectivityManager) pmvilCext.getSystemService(Context.CONNECTIVITY_SERVICE);
            Network netPmvilwork = connectyPmvilManger.getActiveNetwork();
            if (netPmvilwork != null) {
                NetworkCapabilities networkCapabilities = connectyPmvilManger.getNetworkCapabilities(netPmvilwork);
                return networkCapabilities == null?false:networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
            }else{
                return false;
            }
        }
        return false;
    }

}
